# -*- coding:utf-8 -*-

import logging
import colorlog


__all__ = ('Log',)


class Log(object):

    def __init__(self, log_level=logging.INFO):
        # 获取logger对象
        self.logger = logging.getLogger()
        # 指定日志默认输出级别： critical > error > warning > info > debug
        self.logger.setLevel(log_level)
        # 控制台输出日志格式化字符串
        console_fmt = f'%(log_color)s%(asctime)s %(filename)s:::%(funcName)s--%(lineno)d [%(levelname)s] %(message)s'
        # 文件保存日志格式化字符串
        # file_fmt = '%(asctime)s-%(threadName)s-%(filename)s-[line:%(lineno)d]--%(levelname)s: %(message)s'

        color_config = {
            'DEBUG': 'white',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red'
        }

        # 控制台输出
        console_formatter = colorlog.ColoredFormatter(fmt=console_fmt, log_colors=color_config)
        # 文件输出
        # file_formatter = logging.Formatter(fmt=file_fmt)

        # 日志格式配置
        console_handler = logging.StreamHandler()
        # file_handler = logging.FileHandler(filename=name, mode='a', encoding='utf-8')

        # 设置日志格式
        console_handler.setFormatter(console_formatter)

        # logger添加处理器
        # 避免重复打印日志
        if not self.logger.handlers:
            self.logger.addHandler(console_handler)
            # self.logger.addHandler(file_handler)

    # @staticmethod
    # def _get_line_number():
    #     import traceback
    #
    #     # 获取当前堆栈帧
    #     stack = traceback.extract_stack()
    #     # 提取行号
    #     line_no = stack[-1].lineno
    #
    #     return line_no

    def load_logger(self):
        return self.logger


if __name__ == '__main__':
    logger = Log().load_logger()
    logger.info('info')
    logger.warning('warning')
    logger.error('error')
